<?php

namespace Beerus\Modules\Store\Controllers;

use App\Pockets\GridDataModel as pGridDataModel;
use App\Http\Controllers\Controller;
use Biz\model\store\VirtualPhoneRecord;
use Biz\service\Store\StoreBusinessService;
use Biz\service\Store\VirtualPhone;
use Illuminate\Http\Request;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Doraemon\cache\UserNick;

/**
 * 阿里云虚拟手机号的号池管理
 *
 * @category   Module name
 */
class VirtualPhoneController extends Controller
{
    const PAGE_SIZE = 20;
    const BIND_DIRECTIONS = [
        1 => 'UXO',
        2 => 'OXU',
    ];

    public function __construct()
    {
        parent::__construct();
        //隐藏新增按钮--避免隐藏动画出现
        Admin::style('.grid-create-btn{display:none;}');
        Admin::script('$(".pjax-container").attr("id","pjax-container");');
        Admin::script($this->setScript());
    }

    public function index(Request $request, Content $content)
    {
        $request_data = $request->all();

        $page_size = $request->input("per_page", self::PAGE_SIZE);
        $page = $request->input("page", 1);

        $condition = [];
        if (!empty($request_data['user_uid'])) {
            $condition['user_uid'] = $request_data['user_uid'];
        }
        if (!empty($request_data['user_phone'])) {
            $condition['user_phone'] = $request_data['user_phone'];
        }
        if (!empty($request_data['official_phone'])) {
            $condition['official_phone'] = $request_data['official_phone'];
        }
        if (!empty($request_data['direction'])) {
            $condition['direction'] = $request_data['direction'];
        }

        $condition['ORDER'] = ['id' => 'DESC'];
        $condition['LIMIT'] = [
            ($page - 1) * $page_size,
            $page_size
        ];

        $lists = VirtualPhoneRecord::select('*', $condition);

        $total = 0;
        if (!empty($lists)) {
            unset($condition['ORDER']);
            unset($condition['LIMIT']);
            $total = VirtualPhoneRecord::count($condition);
        }

        $store_ids = array_unique(array_column($lists, 'store_id'));
        $store_basics = StoreBusinessService::GetStoreBasicByIds($store_ids);
        $store_basics_kv = array_column($store_basics, null, 'id');

        $gridModel = new pGridDataModel($lists, $total, [
            'perPage' => $page_size
        ]);
        $gridList = Admin::grid(
            $gridModel,
            function (Grid $grid) use ($gridModel, $store_basics_kv) {
                $grid->paginate($gridModel->getPerPage());
                $grid->disableExport();
                $grid->disableRowSelector();

                $grid->filter(function (Grid\Filter $filter) {
                    $filter->disableIdFilter();
                    $filter->column(1 / 2, function ($filter) {
                        $filter->equal('user_uid', '用户UID')->placeholder('请输入uid');
                    });
                    $filter->column(1 / 2, function ($filter) {
                        $filter->equal('user_phone', '用户电话')->placeholder('请输入用户电话');
                    });
                    $filter->column(1 / 2, function ($filter) {
                        $filter->equal('official_phone', '门店电话')->placeholder('请输入门店电话（或官方回拨电话）');
                    });
                    $filter->column(1 / 2, function ($filter) {
                        $filter->equal('direction', '绑定关系')->select(self::BIND_DIRECTIONS);
                    });
                });

                $grid->column("id", 'Id');
                $grid->column('user_phone', '用户手机号');
                $grid->column('virtual_phone', '虚拟手机号(X)');
                $grid->column('official_phone', '门店电话');
                $grid->column('direction', '绑定关系')->display(function () {
                    return self::BIND_DIRECTIONS[$this->direction] ?? '';
                })->help("U用户、X虚拟号、O门店官方");
                $grid->column('subs_id', '绑定关系ID');
                $grid->column("user_uid", '用户uid');
                $grid->column("user_nick", '用户昵称')->display(function () {
                    return UserNick::uid2nick($this->user_uid);
                });
                $grid->column("store_id", '门店id');
                $grid->column("store_name", '门店名称')->display(function () use ($store_basics_kv) {
                    return isset($store_basics_kv[$this->store_id]) ? $store_basics_kv[$this->store_id]['name'] : '';
                });
                $grid->column("addtime", '生效时间')->display(function () {
                    return date("Y-m-d H:i:s", $this->addtime);
                });
                $grid->column("virtual_expire_time", '失效时间');
                $grid->actions(function (Grid\Displayers\Actions $actions) {
                    $actions->disableView();
                    $actions->disableDelete();
                    $actions->disableEdit();
                    if ($actions->row->data_status == VirtualPhoneRecord::STATUS_NORMAL && time() < strtotime($actions->row->virtual_expire_time)) {
                        $actions->prepend('<p><a class="unbind label label-primary" data-id="'.$actions->row->id.'"  href="javascript:void(0);">解绑</a></p>');
                    }
                });
            }
        );

        return $content
            ->header('虚拟手机号列表')
            ->row($gridList);
    }

    public function unbind(Request $request, $id)
    {
        try {
            if (empty($id)) {
                throw new \Exception('参数错误');
            }
            $bind_record = VirtualPhoneRecord::getOneById($id);
            if (empty($bind_record)) {
                throw new \Exception("虚拟号绑定记录不存在");
            }
            if ($bind_record['data_status'] == VirtualPhoneRecord::STATUS_DELETE) {
                throw new \Exception("已解绑");
            }
            $virtual_expire_time = $bind_record['virtual_expire_time'];
            if (time() > strtotime($virtual_expire_time)) {
                throw new \Exception("绑定关系已过期，无需解绑");
            }
            $virtual_phone = $bind_record['virtual_phone'];
            $subs_id = $bind_record['subs_id'];
            $nResult = VirtualPhone::unbindVirtualPhone($virtual_phone, $subs_id);
            if ($nResult) {
                VirtualPhoneRecord::updateInfo($bind_record['id'], [
                        'data_status' => VirtualPhoneRecord::STATUS_DELETE,
                        'virtual_expire_time' => time() - 1
                    ]
                );
                $status = true;
                $message = '操作成功';
            } else {
                $status = false;
                $message = '操作失败';
            }
        } catch (\Exception $e) {
            $status = false;
            $message = $e->getMessage();
        }
        return response()->json(compact('status', 'message'));
    }

    private function setScript()
    {
        return <<<SCRIPT
            $('.unbind').unbind('click').click(function(){
                var id= $(this).data('id');
                layer.confirm('确定要取消虚拟号绑定吗？', {
                    btn: ['确定', '取消']
                }, function (index) {
                    layer.close(index);
                    let url = '/admin/store/virtualphone/unbind/'+ id;
                    let params = {};
                    $.post(url, params , function (result) {
                        if (result.status == 1) {
                            layer.msg(result.message);
                            setTimeout(function () {
                                parent.window.location.reload();
                            }, 2000);
                        } else {
                            layer.msg(result.message);
                        }
                    });
                });
            });
SCRIPT;
    }

}
